/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 25228
 * Date: 2024-10-02
 * Time: 18:23
 */
public class HashBucket {
    private static class Node {
        private int key;
        private int value;
        Node next;


        public Node(int key, int value) {
            this.key = key;
            this.value = value;
        }
    }


    private Node[]  array;
    private int size;   // 当前的数据个数
    private static final double LOAD_FACTOR = 0.75;
    private static final int DEFAULT_SIZE = 8;//默认桶的大小

    public void put(int key, int value) {
        //确认对应的链表
        int index=key%array.length;
        Node cur=array[index];
        //寻找该链表有没有key重复的，若有，更新对应的value值
        while (cur!=null){
            if(cur.key==key) {
                cur.value = value;
                return ;
            }
            cur=cur.next;
        }
        //若没有，采用头插法插入
        Node per=new Node(key, value);
        per.next=array[index];
        array[index]=per;
        size++;
        //计算负载因子，视情况扩容
        double load=loadFactor();
        if(load>=LOAD_FACTOR){
            resize();
        }
    }


    private void resize() {
        Node[] newArray=new Node[array.length*2];
        for (int i = 0; i < array.length; i++) {
            Node cur=array[i];
            while (cur!=null){
                int index=cur.key%newArray.length;
                Node curN=cur.next;
                cur.next=newArray[index];
                newArray[index]=cur;
                cur=curN;
            }
        }
        array=newArray;
    }


    private double loadFactor() {
        return size * 1.0 / array.length;
    }


    public HashBucket() {
        array=new Node[10];
        size=0;
    }


    public int get(int key) {
        int index=key%array.length;
        Node cur=array[index];
        while (cur!=null){
            if(cur.key==key){
                return cur.value;
            }
            cur=cur.next;
        }
        return -1;
    }
}
